package vip.xiaonuo.megvii.captures.handle.impl;

import com.alibaba.fastjson.JSON;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Service;
import org.springframework.test.annotation.Rollback;
import org.springframework.transaction.annotation.Transactional;
import vip.xiaonuo.facedoor.modular.memberfeatures.entity.MemberFeatures;
import vip.xiaonuo.facedoor.modular.memberfeatures.param.MemberFeaturesParam;
import vip.xiaonuo.facedoor.modular.memberfeatures.service.MemberFeaturesService;
import vip.xiaonuo.facedoor.modular.memberuser.entity.MemberUser;
import vip.xiaonuo.facedoor.modular.memberuser.param.MemberUserParam;
import vip.xiaonuo.facedoor.modular.memberuser.service.MemberUserService;
import vip.xiaonuo.megvii.captures.handle.ActivePushHandleImpl;
import vip.xiaonuo.megvii.captures.model.FaceDistinguishEntity;
import vip.xiaonuo.megvii.captures.model.ShapeDistinguishEntity;
import vip.xiaonuo.megvii.captures.model.base.BindingInfo;
import vip.xiaonuo.modular.megviicapturedata.service.MegviiCaptureDataService;
import vip.xiaonuo.modular.megviidistinguishdata.entity.MegviiDistinguishData;
import vip.xiaonuo.modular.megviidistinguishdata.service.MegviiDistinguishDataService;
import vip.xiaonuo.modular.megviipushdata.entity.MegviiPushData;
import vip.xiaonuo.modular.megviipushdata.service.MegviiPushDataService;
import vip.xiaonuo.modular.megviitrackidrelate.entity.MegviiTrackidRelate;
import vip.xiaonuo.modular.megviitrackidrelate.service.MegviiTrackidRelateService;

import javax.annotation.Resource;
import javax.validation.constraints.NotNull;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 人脸识别的数据处理
 */
@Service
public class FaceDistinguishHandlerService extends PushDataBaseHandler implements ActivePushHandleImpl<FaceDistinguishEntity> {

    @Resource
    private MegviiDistinguishDataService distinguishDataService;

    @Resource
    private MemberFeaturesService featuresService;

    @Resource
    private MemberUserService userService;



    @Override
    public void handle(@NotNull MegviiPushData data) {
        try{
            String text = data.getValue();
            FaceDistinguishEntity entity = JSON.parseObject(text,FaceDistinguishEntity.class);

            // 业务数据转换与保存
            this.saveData(entity);

            // 保存原始数据处理结果
            data.setStatus(1);
            pushDataService.saveOrUpdate(data);
        }catch (Exception e){
            data.setStatus(2);
            data.setFailReason(ExceptionUtils.getMessage(e));
            pushDataService.saveOrUpdate(data);
        }
    }

    @Override
    public void saveData(FaceDistinguishEntity entity) {


        List<BindingInfo> binds = entity.getBindingInfo();
        long trackId = entity.getTrack_id();

        // 保存关联关系表
        List<MegviiTrackidRelate> relates  = createRelates(trackId,binds);
        if(relates!=null && relates.size()>0){
            relateService.saveOrUpdateBatch(relates);
        }

        MegviiDistinguishData data = new MegviiDistinguishData();

        data.setTrackId(entity.getTrack_id());

        // 保存图片
        Long imgId  = this.saveImg(entity.getPhoto(),fileService);
        data.setImgId(imgId);
        Long fullImgId = this.saveImg(entity.getFullImage(),fileService);
        data.setFullImgId(fullImgId);

        data.setDeviceId(entity.getDevice_id());
        data.setChannelName(entity.getScreen_token());

        data.setGender(entity.getGender());
        data.setAge(entity.getAge());
        data.setFmp(new BigDecimal( entity.getFmp() ).setScale(2, RoundingMode.HALF_DOWN));
        data.setRespirator(entity.getFaceAttr().getRespirator().getRespiratorWear());
        data.setGlasses(entity.getFaceAttr().getGlasses().getGlassLeftWear());
        data.setHair(entity.getFaceAttr().getHair());
        data.setBeard(entity.getFaceAttr().getBeard());

        data.setCompareScore(new BigDecimal(entity.getConfidence()).setScale(2, RoundingMode.HALF_DOWN));
        data.setLibImgId(this.getImg(entity.getImageID()));

        data.setStrangerFlag(entity.getStranger_flag());

        data.setCaptureTime(new Date(entity.getTimestamp()));

        // TODO 补充其他信息

        distinguishDataService.save(data);
    }

    private Long getImg(String imageID) {
        // TODO 先不考虑本地图片丢失的问题
        MemberFeaturesParam param = new MemberFeaturesParam();
        param.setDelFlag(null);
        param.setImageId(imageID);
        MemberFeatures memberFeatures;
        try{
            memberFeatures = featuresService.list(param).get(0);
        }catch (IndexOutOfBoundsException e){
            return null;
        }
        MemberUser user = userService.getById(memberFeatures.getDwMemberUserId());
        if(user==null){
            return null;
        }else {
            return this.getImgId(user.getPhoto());
        }
    }

    private Long getImgId(String path){
        String reg = "[^0-9]";
        Pattern p = Pattern.compile(reg);
        Matcher m = p.matcher(path);
        String id = m.replaceAll("").trim();
        return Long.parseLong(id);
    }

}
